package com.tanhua.sso.Utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class SendSms {

    public String sendSms(String mobile) throws IOException {
        //使用类加载器读取配置文件
        InputStream inputStream = SendSms.class.getClassLoader().getResourceAsStream("aliyun.properties");
        Properties properties = new Properties();
        properties.load(inputStream);


        String regionId = properties.getProperty("aliyun.sms.regionId");
        String accessKeyId = properties.getProperty("aliyun.sms.accessKeyId");
        String accessKeySecret = properties.getProperty("aliyun.sms.accessKeySecret");
        String domain = properties.getProperty("aliyun.sms.domain");
        String signName = properties.getProperty("aliyun.sms.signName");
        String templateCode = properties.getProperty("aliyun.sms.templateCode");


        DefaultProfile profile = DefaultProfile.getProfile(regionId,
                accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(domain);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", signName); //签名名称
        request.putQueryParameter("TemplateCode", templateCode); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                return code;
            }
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + mobile, e);
        }
        return null;
    }
}
